package org.dicker.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dicker.biz.impl.ManagerBizImpl;
import org.dicker.entity.ManagerInfo;



@WebFilter(filterName="Auth",urlPatterns="/*")
public class AuthFilter implements Filter{

	

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		String uri = req.getRequestURI();
		if(uri.endsWith("login.jsp")
		|| uri.endsWith(".css")
		|| uri.endsWith(".js")
		|| uri.contains("/images")
		|| uri.contains("/public")
		|| uri.contains("/upload")
		|| uri.endsWith("/lib")
		|| uri.contains("/vcode")
		|| uri.contains("api/")
		|| uri.contains("/manager")
		   ){
			chain.doFilter(request, response);
			return;
		}
		
		boolean auth = false;
		ManagerInfo man = (ManagerInfo)req.getSession().getAttribute("USER_LOGIN");
		if(man==null) {
			String auth_id = getCookie(req,"COOKIE_ID");
			if(auth_id!=null){
				man = new ManagerBizImpl().selectManagerID(Integer.valueOf(auth_id));
				if(man!=null) {
					req.getSession().setAttribute("USER_LOGIN",man);
					auth = true;
				}
			}
		}else 
			auth = true;
		
		if(auth)
			chain.doFilter(request, response);
		else
			res.sendRedirect("/big-birds/login.jsp");
	}

	public static String getCookie(HttpServletRequest req,String cookname) {
		String obj = null;
		for(Cookie c:req.getCookies()) {
			if(cookname.equals(c.getName())) {
				obj = c.getValue();
				break;
			}
		}
		return obj;
	}

	
	
	@Override
	public void destroy() {
		
	}
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}
}
